<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
  <meta http-equiv="content-type" content="text/html; charset=UTF-8">
  <title>时间戳转换</title>
  <script type="text/javascript">
    // 当前时间和时间戳
    function nowtime(){
      var nowDateObj = new Date();
      var nowTime = parseInt(nowDateObj.getTime() / 1000);
      var nowDate = obj_to_date(nowDateObj);

      document.getElementById("nowdate").innerText = nowDate;
      document.getElementById("nowtime").innerText = nowTime;
    }

    // 时间戳转换为时间
    function todate(){
      var timestamp = parseInt(document.getElementById("timestamp").value) * 1000;
      var DateObj = new Date(timestamp);

      var resultDate = obj_to_date(DateObj);

      document.getElementById("result_1").innerText = resultDate;
    }

    // 时间转换为时间戳
    function totime(){
      var datetime = document.getElementById("datetime").value;
      var datetimeElement = datetime.split(' ');
      var dateElement = datetimeElement[0].split('-');
      var timeElement = datetimeElement[1].split(':');
      var DateObj = new Date(dateElement[0], dateElement[1]-1, dateElement[2], timeElement[0], timeElement[1], timeElement[2], 0);

      var resultTime = parseInt(DateObj.getTime() / 1000);

      document.getElementById("result_2").innerText = resultTime;
    }

    // 时间对象转换为文字
    function obj_to_date(obj){
      var resultDate = obj.getFullYear() + "-"
                    + (obj.getMonth() + 1) + "-"
                    + obj.getDate() + " "
                    + obj.getHours() + ":"
                    + obj.getMinutes() + ":"
                    + obj.getSeconds();

      return resultDate;
    }

    //var d2 = new Date(d);
    //alert(d2.toString());
  </script>
</head>

<body onload="javascript: nowtime();">
<div style="padding-top: 100px; padding-left: 25%;">

  <table>
    <tr height="45px">
      <td width="75px">Now time:</td>
      <td width="260px"><span id="nowdate"></span></td>
      <td width="260px">Tiemstamp: <span id="nowtime"></span></td>
    </tr>
    <tr height="45px">
      <td>Tiemstamp:</td>
      <td>
        <input type="text" name="timestamp" id="timestamp" value="" />
        <input type="button" value="To time" onclick="javascript: todate();" />
      </td>
      <td>
        <span id="result_1"></span>
      </td>
    </tr>
    <tr height="45px">
      <td>Time:</td>
      <td>
        <input type="text" name="datetime" id="datetime" value="" />
        <input type="button" value="To stamp" onclick="javascript: totime();" />
      </td>
      <td>
        <span id="result_2"></span>
      </td>
    </tr>
  </table>

</div>

</body>
</html>